package cn.iocoder.yudao.module.product.util;

import org.docx4j.Docx4J;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;

import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * 转换xml格式的doc或docx文档为docx
 */
public class XmlDocToDocxUtil {

    /**
     * 转换执行方法,转换后和原始路径
     *
     * @param xmlPath 原始路径
     * @return
     */
    public static String invoke(String xmlPath) {
        if (xmlPath.endsWith(".doc") || xmlPath.endsWith(".docx")) {
            //不仅可以将doc转为docx，还可以将freemarker生成的xml类型的docx转为正常的文档
            String docxPath = xmlPath.replaceAll("(\\.docx)|(\\.doc)", ".docx");
            try (FileInputStream inputStream = new FileInputStream(xmlPath);) {
                WordprocessingMLPackage wmlPackage = Docx4J.load(inputStream);
                //转换为DOCX
                try (FileOutputStream docx = new FileOutputStream(docxPath);) {
                    Docx4J.save(wmlPackage, docx, Docx4J.FLAG_SAVE_ZIP_FILE);
                    xmlPath = docxPath;
                }
            } catch (Exception e) {
                System.out.println((xmlPath + ":不需要转换:" + e.getLocalizedMessage()));
            }
        }
        System.out.println("WORD 路径：" + xmlPath);
        return xmlPath;
    }

    public static void main(String[] args) {
        XmlDocToDocxUtil.invoke("C:\\Users\\Administrator\\Desktop\\温室气体盘查报告.doc");
    }

}
